package com.fanfq.itrack.ui;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.fanfq.itrack.CustomMenu.OnMenuItemSelectedListener;
import com.fanfq.itrack.Constant;
import com.fanfq.itrack.CustomMenuItem;
import com.fanfq.itrack.Export;
import com.fanfq.itrack.Gps;
import com.fanfq.itrack.R;
import com.fanfq.itrack.model.Ride;
import com.fanfq.util.DBUtil;
import com.fanfq.util.GPSUtil;

public class RecordActivity extends Activity implements OnClickListener {

	private LocationManager mLocationManager;
	private Location mLocation;
	private Criteria mCriteria;
	private String provider;
	private static final int EDIT_DIALOG = 1;
	private DBUtil mDBUtil;
	private Gps storeDate;//重复数据只保留一份
	
	private TextView signal;
	private TextView time;
	private TextView distance;
	private TextView speed;

	private Button start;

	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private double templon = 0;
	private double templat =0;
	private double distance_value = 0;

	private Timer timer;
	int recLen = 0;

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				recLen++;
				time.setText(String.format("%02d:%02d:%02d", recLen / 3600,
						(recLen / 60) > 59 ? recLen / 3600 : recLen / 60,
						recLen % 60));
				break;
			}
			super.handleMessage(msg);
		}
	};
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.record);

		signal = (TextView) findViewById(R.id.signal);
		time = (TextView) findViewById(R.id.timer);
		distance = (TextView) findViewById(R.id.distance);
		speed = (TextView) findViewById(R.id.speed);
		start = (Button) findViewById(R.id.start);
		start.setOnClickListener(this);
		
		storeDate = new Gps();
        this.mDBUtil = new DBUtil(this);
        initLocation();//初始化GPS定位
        
     // Restore preferences
        SharedPreferences settings = getSharedPreferences(Constant.SETTING_PREF, 0); // 获取一个SharedPreferences对象
        Constant.PAGE_SIZE = Integer.valueOf(settings.getString(Constant.PAGE_SIZE_PREF, "20"));
        Constant.EXPORT_XML = settings.getBoolean(Constant.EXPORT_XML_PREF, true);
        Constant.EXPORT_CSV = settings.getBoolean(Constant.EXPORT_CSV_PREF, true);
        Constant.EXPORT_GPX = settings.getBoolean(Constant.EXPORT_GPX_PREF, true);
        
	}
	
	private static boolean isStarted = false;
	private static String rideId;
	private static int  pos;

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.start:
			if(isStarted){
		        new ExportaAsyncTask().execute();
				timer.cancel(); //退出计时器
				start.setText("Start");
//				try{
//					mDBUtil.deleteData();
//					Toast.makeText(this, "数据已成功清除", 1).show(); 
//				}catch (Exception e) {
//					Toast.makeText(this, "数据清除失败", 1).show(); 
//				}
				isStarted = false;
			}else{
				TimerTask task = new TimerTask() {
					public void run() {
						Message message = new Message();
						message.what = 1;
						handler.sendMessage(message);
					}
				};
				
				timer = new Timer();
				timer.schedule(task,1000, 1000); //延时1000ms后执行，1000ms执行一次
		        start.setText("Recording...");
		        isStarted = true;
		        
		        //add a ride
		        Ride ride = new Ride();
		        ride.setId(UUID.randomUUID().toString());
		        ride.setStart_timestamp(System.currentTimeMillis());
		        ride.setComments_count(0);
		        ride.setKudos_count(0);
		        ride.setUser_id("fan");
		        mDBUtil.addRide(ride);
				
		        rideId = ride.getId();
		        pos = 0;
			}
			break;
		default:
			break;
		}
	}
	
	private class ExportaAsyncTask extends AsyncTask<Object, Void, String>{

		private ProgressDialog pd;
		
		protected void onPostExecute(String string) {
			pd.cancel();
			Toast.makeText(RecordActivity.this, string, 1).show(); 
		}
		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(RecordActivity.this);
			pd.setMessage("数据导出中...");
			pd.setCancelable(false);
			pd.show();
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(Object... params) {
			return Export.export(mDBUtil.getGpsByRideId(rideId),false);
		}
		
	}
	
	/**
	 * @Title: finish
	 * @Description: 结束GPS定位服务
	 * @param void    
	 * @return void    
	 * @throws 
	 */
	@Override
	public void finish() {
		mLocationManager.removeUpdates(locationListener);
		timer.cancel(); //退出计时器
		super.finish();
	}
	
	/**
	 * @Title: initLocation
	 * @Description: GPS初始化
	 * @param void
	 * @return void    
	 * @throws 
	 */
	private void initLocation() {
		mLocationManager = (LocationManager)getSystemService(this.LOCATION_SERVICE);
		if (mLocationManager.isProviderEnabled(mLocationManager.GPS_PROVIDER)) {
			mCriteria = new Criteria();
			mCriteria.setAccuracy(Criteria.ACCURACY_COARSE);// 精度
			mCriteria.setAltitudeRequired(true);// 显示海拔
			mCriteria.setBearingRequired(true);// 显示方向
			mCriteria.setSpeedRequired(true);// 显示速度
			mCriteria.setCostAllowed(true);// 不允许有花费
			mCriteria.setPowerRequirement(Criteria.POWER_LOW);// 低功耗
			provider = mLocationManager.getBestProvider(mCriteria, true); // 获取GPS信息
			// 位置变化监听,默认5秒一次,距离10米以上
			mLocationManager.requestLocationUpdates(provider, 1000, 0,
					locationListener);
		} else {
			showInfo(null, Constant.GPS_LOST);
		}
	}
	
	/**	 初始化GPS监听	 */
	private final LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location arg0) {
			showInfo(getLastPosition(), Constant.GPS_AUTO_LOCAL);
		}
		public void onProviderDisabled(String arg0) {
			showInfo(null, Constant.GPS_LOST);
		}
		public void onProviderEnabled(String arg0) {
		}
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		}
	};
	
	/**
	 * @Title: getLastPosition
	 * @Description: 获取GPS数据
	 * @param void
	 * @return Gps    
	 * @throws 
	 */
	private Gps getLastPosition() {
		Gps result = new Gps();
		if(null != provider){
			mLocation = mLocationManager.getLastKnownLocation(provider);
		}
		if (mLocation != null) {
			result.setLatitude(mLocation.getLatitude());
			result.setLongitude(mLocation.getLongitude());
			result.setAltitude(mLocation.getAltitude());
			result.setBearing(mLocation.getBearing());
			result.setSpeed(mLocation.getSpeed());
			result.setTimestamp(mLocation.getTime());
		}
		return result;
	}
	
	/**
	 * @Title: showInfo
	 * @Description: debug GPS数据
	 * @param Gps cdata, int infotype
	 * @return void    
	 * @throws 
	 */
	private void showInfo(Gps cdata, int infotype) {
		if (cdata == null) {
			if (infotype == Constant.GPS_LOST) {
				Toast.makeText(this, "GPS功能已关闭", 1).show();
				Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
		        startActivityForResult(intent,0); //此为设置完成后返回到获取界面
			}
		} else {
//			Toast.makeText(
//					this,
//					String.format("纬度:%f", cdata.getLatitude()) + ","
//							+ String.format("经度:%f", cdata.getLongitude())
//							+ "," + String.format("海拔:%f", cdata.getHigh())
//							+ "," + String.format("方向:%f", cdata.getDirect())
//							+ "," + String.format("速度:%f", cdata.getSpeed())
//							+ "," + String.format("GPS时间:%s", cdata.getGpsTime())
//							+ "," + String.format("数据类型:%d", cdata.getInfoType()), 1)
//					.show();
			//跟新页面的数据显示 todo
//			this.lat.setText(String.format("%f",cdata.getLatitude()));
//			this.lon.setText(String.format("%f",cdata.getLongitude()));
//			this.direct.setText(String.format("%f",cdata.getDirect()));
//			this.speed.setText(String.format("%f",cdata.getSpeed()));
//			this.high.setText(String.format("%f",cdata.getHigh()));
			
			
			
			if(null!=storeDate && storeDate.equals(cdata)){
				return ;
			}else if(cdata.getLatitude() !=0 && cdata.getLongitude()!=0){
				if(templon!=0&&templat!=0&&pos>1){
					//double sp = 6371004*Math.cos(Math.sin(templon)*Math.sin(cdata.getLongitude())+Math.cos(templon)*Math.cos(cdata.getLongitude())*Math.cos(templat-cdata.getLatitude()))*3.14/180;
					this.speed.setText(String.format("%.1f", cdata.getSpeed()/1000*3600));
					if(cdata.getSpeed()!=0){
						distance_value += GPSUtil.getDistance(templat, templon, cdata.getLatitude(), cdata.getLongitude());
						this.distance.setText(String.format("%.1f", distance_value));
					}
				}
				templat = cdata.getLatitude();
				templon = cdata.getLongitude();
				
				signal.setText("Satellite Count: "+getStarCount());
				
				if(isStarted){
					cdata.setDistance(distance_value);
					cdata.setFiltered(pos == 0 ? 1:0);
					cdata.setPos(pos++);
					cdata.setRide_id(rideId);
					cdata.setDevice_time(System.currentTimeMillis());
					cdata.setElapsed_time(recLen);
					
					this.mDBUtil.addGpsData(cdata);//数据存储
					storeDate = cdata;
				}
			}
		}
	}
	
	//获取当前已收到卫星的个数
	private int getStarCount(){
//		LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Iterator<GpsSatellite> iterator = mLocationManager.getGpsStatus(null).getSatellites().iterator();

		int count = 0;
		while (iterator.hasNext()) {
		        count++;
		        iterator.next();
		}
		return count;
	}

}
